package com.esb.transport.handler.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import com.esb.transport.handler.codec.serialization.Codec;
import com.esb.transport.protocal.Invocation;

public class MessageEncoder extends MessageToByteEncoder<Invocation> {
	
	private static final byte[] LENGTH_PLACEHOLDER = new byte[2];
	private Codec codec;

	public MessageEncoder(Codec codec) {
		this.codec = codec;
	}
	
	@Override
	protected void encode(ChannelHandlerContext ctx, Invocation msg, ByteBuf out) throws Exception {
		int startIdx = out.writerIndex();
        byte[] bytes = codec.encode(msg);
        out.writeBytes(LENGTH_PLACEHOLDER);
        out.writeBytes(bytes);

        out.setShort(startIdx, bytes.length);
	}

}
